package com.heima.article.service;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.heima.article.entity.ApArticle;
import com.heima.article.entity.ApArticleContent;
import com.heima.common.minio.service.MinIOService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * @author: itheima
 * @create: 2022-08-01 12:16
 */
@Service
public class ArticleHtmlTask {

    /**
     * freemarker.template包下
     */
    @Autowired
    private Configuration configuration;

    @Autowired
    private IApArticleService articleService;

    @Autowired
    private IApArticleContentService contentService;

    @Autowired
    private MinIOService minIOService;


    /**
     * 生成文章静态页文件，将文件上传到MinIO，更新文章静态页字段
     * @param articleId
     */
    @Async("leadnewsExecutor")
    public void createHtmlUpload(Long articleId) {
        try {
            //1.查询文章信息--文章、文章内容
            ApArticle article = articleService.getById(articleId);

            LambdaQueryWrapper<ApArticleContent> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(ApArticleContent::getArticleId, articleId);
            ApArticleContent articleContent = contentService.getOne(queryWrapper);


            //2.加载模板文件得到模板对象
            Template template = configuration.getTemplate("article.ftl");

            //3.生成html文件
            //3.1 准备模板需要模型数据
            Map<String, Object> modelMap = new HashMap<>();
            modelMap.put("content", JSON.parseArray(articleContent.getContent()));
            modelMap.put("item", article);
            //3.2 写数据对象
            StringWriter writer = new StringWriter();
            template.process(modelMap, writer);
            //4.将文件上传MinIO
            InputStream inputStream = new ByteArrayInputStream(writer.toString().getBytes());

            String htmlUrl = minIOService.upload(articleId + ".html", inputStream, "text/html");

            //5.更新文章表同步静态页地址
            article.setStaticUrl(htmlUrl);
            article.setSyncStatus(1);
            articleService.updateById(article);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
